package com.zm.tools.util.core;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

/**
 * @author zoum
 * @date 2018/6/6 18:34.
 */
public class RSAUtil {

    /**
     * 生成密钥
     * @param algorithm 算法， 如：RSA
     * @param keysize 长度， 如：2048
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair getKeyPair(String algorithm, int keysize)throws NoSuchAlgorithmException{
        KeyPairGenerator gen = KeyPairGenerator.getInstance(algorithm);
        gen.initialize(keysize);
        KeyPair pair = gen.generateKeyPair();
        return pair;
    }

    public static PrivateKey getPrivateKey(String algorithm, int keysize) throws NoSuchAlgorithmException{
        return getKeyPair(algorithm, keysize).getPrivate();
    }

    public static PublicKey getPublicKey(String algorithm, int keysize) throws NoSuchAlgorithmException{
        return getKeyPair(algorithm, keysize).getPublic();
    }

    /**
     * 签名
     * @param privateKey 私钥
     * @param algorithm 签名算法，如：SHA1withRSA
     * @param data  签名的原数据
     * @throws Exception
     */
    public static byte[] sign(PrivateKey privateKey, String algorithm, byte[] data) throws Exception{
        //SHA1withRSA算法进行签名
        Signature sign = Signature.getInstance(algorithm);
        sign.initSign(privateKey);
        //更新用于签名的数据
        sign.update(data);
        return sign.sign();
    }

    /**
     * 验证签名
     * @param publicKey 公钥
     * @param algorithm 签名算法，如：SHA1withRSA
     * @param data 验签的数据
     * @return
     */
    public static boolean verify(PublicKey publicKey, String algorithm, byte[] data, byte[] signature) throws Exception{
        Signature verifySign = Signature.getInstance(algorithm);
        verifySign.initVerify(publicKey);
        //用于验签的数据
        verifySign.update(data);
        return verifySign.verify(signature);
    }
}
